from PreRec.POP.Trainer import Trainer
from tqdm import tqdm
from typing import Dict, List
import os


class Recommender:
    def __init__(self, hyper_params):
        self.hyper_params = hyper_params

        self.trainer = Trainer(hyper_params)
        self.user_cnt = self.trainer.file_loader.reader_cnt
        self.item_cnt = self.trainer.file_loader.book_cnt

        self.popularity = self.trainer.popularity

    def recommend(self, max_cnt=500) -> List[int]:
        print('POP: Start Popular recommendation...')
        result: List[int] = sorted(
            self.popularity.items(), key=lambda x: x[1], reverse=True)

        if len(result) > max_cnt:
            result = result[:max_cnt]

        rank = [i[0] for i in result]

        # Save result to result/hot_books.txt
        os.makedirs('result', exist_ok=True)
        with open(os.path.join('result', 'hot_books.txt'), 'wt') as f:
            for i in range(len(rank)):
                f.write(f'{rank[i]};{result[i][1]}\n')

        print('POP: Finished Popular recommendation.')
        return rank


if __name__ == '__main__':
    hyper_params = {
        'dataset_path': '../datasets/lib.txt'
    }

    recommender = Recommender(hyper_params)
    result = recommender.recommend(max_cnt=500)

    print(result)
